import { PagedListingComponentBase } from '/@/shared/component-base';
import { EditionSelect } from '/@/app/admin-shared';
import { defineComponent } from 'vue';
import {
  PlusOutlined,
  DeleteOutlined,
  EditOutlined,
  LoginOutlined,
  CodepenOutlined,
  UnlockOutlined,
  CheckCircleTwoTone,
  CloseCircleTwoTone,
} from '@ant-design/icons-vue';
import { TenantServiceProxy, EntityDto, TenantListDto } from '/@/shared/service-proxies';
import CreateTenantComponent from './create-tenant/create-tenant.vue';
import EditTenantComponent from './edit-tenant/edit-tenant.vue';
import CommonLookupComponent from './common-lookup/common-lookup.vue';
import EditTenantFeaturesComponent from './edit-tenant-features/edit-tenant-features.vue';
import { impersonationService } from '/@/shared/auth/index';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { EVENT_BTN_ENUM } from '/@/shared/components/g-dynamic-table/enums/event-btn-enum';
import { AppConsts } from '/@/abpPro/AppConsts';
dayjs.locale('zh-cn');
export default defineComponent({
  name: 'Tenants',
  components: {
    EditionSelect,
    PlusOutlined,
    DeleteOutlined,
    EditOutlined,
    LoginOutlined,
    CodepenOutlined,
    UnlockOutlined,
    CheckCircleTwoTone,
    CloseCircleTwoTone,
    CreateTenantComponent,
    EditTenantComponent,
    CommonLookupComponent,
  },
  mixins: [PagedListingComponentBase],
  data() {
    return {
      tenantService: new TenantServiceProxy(),
      dataList: [] as TenantListDto[],
      selectedEdition: {
        value: 0,
      },

      item: {} as TenantListDto,
      /** 选中 */
      selectItems: [] as any[],
      editionId: '' as any,
    };
  },
  methods: {
    /**
     * 获取数据
     */
    fetchDataList(otherQuery) {
      const { maxResultCount, skipCount, sorting, TenantNameOrTenancyCode, Edition, OrderDate } = (
        this.$refs.table as any
      ).getSearchProps();
      return new Promise((resolve, reject) => {
        this.tenantService
          .getPaged(
            null,
            null,
            !OrderDate ? undefined : OrderDate[0],
            !OrderDate ? undefined : OrderDate[1],
            Edition,
            TenantNameOrTenancyCode,
            sorting,
            !!otherQuery ? otherQuery.maxResultCount : maxResultCount,
            !!otherQuery ? otherQuery.skipCount : skipCount,
          )
          .finally(() => {
            // finishedCallback!();
          })
          .then((res) => {
            resolve(res);
            // this.showPaging(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /**
     * 版本选择
     */
    selectedEditionChange(e) {
      this.editionId = e ? e.value : null;
      this.getSearchData();
    },
    /**
     * 订阅日期改变
     */
    subscribableDateChange(e) {
      if (!e) {
        this.subscribableDateRange = [null, null];
      } else {
        this.subscribableDateRange = e;
      }
      this.getSearchData();
    },
    /**
     * 创建时间改变
     */
    createDateChange(e) {
      if (!e) {
        this.createDateRange = [null, null];
      } else {
        this.createDateRange = e;
      }
      this.getSearchData();
    },
    /**
     * 新建租户
     */
    createNewTenant(item?: TenantListDto) {
      this.modalHelper.create(CreateTenantComponent, null).subscribe((res) => {
        if (res) {
          (this.$refs.table as any).reloadGoFirstPage();
        }
      });
    },
    /**
     * 编辑
     */
    edit(item?: TenantListDto) {
      this.modalHelper
        .create(EditTenantComponent, { pageDataList: [item?.id] })
        .subscribe((res) => {
          if (res) {
            (this.$refs.table as any).reloadGoFirstPage();
          }
        });
    },
    closed(tableId) {
      console.log(this.selectItems);
      this.impersonateUser(tableId, this.selectItems[0]);
    },
    /**
     * 批量编辑
     */
    bulkEdit() {
      this.selectItems = [];
      let arr = (this.$refs.table as any).getSelectRowKeys();
      if (arr.length < 1) {
        return this.notify.warn(this.l('PleaseSelectAtLeastOneItem'));
      }
      this.selectItems = arr;
      this.modalHelper
        .create(EditTenantComponent, { pageDataList: this.selectItems })
        .subscribe((res) => {
          if (res) {
            (this.$refs.table as any).reloadGoFirstPage();
          }
        });
    },
    /**
     * 批量删除
     */
    batchDelete() {
      const table = this.$refs.table as any;
      if (table.getSelectRowKeys().length <= 0) {
        this.notify.warn(this.l('PleaseSelectAtLeastOneItem'));
        return;
      }
      const ids = table.selectedRowKeys.map((o) => {
        return new EntityDto({ id: o });
      });
      this.message.confirm(
        this.l('ConfirmDeleteXItemsWarningMessage', table.getSelectRowKeys().length),
        '',
        (res: any) => {
          if (res) {
            (this.$refs.table as any).setLoading(true);
            this.tenantService
              .batchDelete(ids)
              .finally(() => {
                (this.$refs.table as any).setLoading(false);
              })
              .then(() => {
                (this.$refs.table as any).reloadGoFirstPage();
                this.notify.success(this.l('SuccessfullyDeleted'));
              });
          }
        },
      );
    },
    /**
     * 单个删除
     */
    deleteItem(item: TenantListDto) {
      if ((item as any).isStatic) {
        this.notify.warn(
          this.l('XUserCannotBeDeleted', AppConsts.userManagement.defaultAdminUserName),
        );
        return;
      }
      (this.$refs.table as any).setLoading(true);
      this.tenantService
        .delete(item.id)
        .finally(() => {
          (this.$refs.table as any).setLoading(false);
        })
        .then(() => {
          (this.$refs.table as any).reloadGoFirstPage();
          this.notify.success(this.l('SuccessfullyDeleted'));
        });
    },
    /**
     * 使用此租户登录
     */
    tenantImpersonateLogin(item: TenantListDto) {
      this.modalHelper.create(CommonLookupComponent, { pageDataList: item.id }).subscribe((res) => {
        if (res) {
          this.impersonateUser(res, item.id);
        }
      });
    },
    /**
     * 特性参数列表
     */
    changeTenantFeatures(item: TenantListDto) {
      this.modalHelper
        .create(EditTenantFeaturesComponent, { pageDataList: item.id })
        .subscribe((res) => {
          if (res) {
            (this.$refs.table as any).reloadGoFirstPage();
          }
        });
    },
    /**
     * 解锁
     */
    unlockTenantAdminUser(item: TenantListDto) {
      const entitys = new EntityDto();
      entitys.id = item.id;
      this.isTableLoading = true;
      this.tenantService
        .unlockTenantAdmin(entitys)
        .finally(() => {
          this.isTableLoading = false;
        })
        .then(() => {
          this.notify.success(this.l('UnlockedTenandAdmin'));
        })
        .catch((err) => {});
    },
    impersonateUser(item, id) {
      impersonationService.impersonate(parseInt(item.value), id);
    },
    /**
     * 按钮回调事件
     */
    handleActionClick(event: string, item?: any) {
      console.log(event);
      switch (event) {
        case EVENT_BTN_ENUM.CREATE:
          this.createNewTenant();
          break;
        case EVENT_BTN_ENUM.DELETE:
          this.deleteItem(item);
          break;
        case EVENT_BTN_ENUM.BULK_EDIT:
          this.bulkEdit();
          break;
        case EVENT_BTN_ENUM.EDIT:
          this.edit(item);
          break;
        case EVENT_BTN_ENUM.BULK_DELETE:
          this.batchDelete();
          break;
        case EVENT_BTN_ENUM.LOGIN_AS_THIS_USER:
          this.tenantImpersonateLogin(item);
          break;
        case EVENT_BTN_ENUM.UNLOCK:
          this.unlockTenantAdminUser(item);
          break;
        case EVENT_BTN_ENUM.FEATURES:
          this.changeTenantFeatures(item);
          break;
        default:
          break;
      }
    },
  },
});
